﻿using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Inovout.Web.Http
{
    public class JsonGZipMediaTypeFormatter : JsonMediaTypeFormatter
    {
        public JsonGZipMediaTypeFormatter()
        {
            //解析XDomainRequest没有ContentType的问题。
            base.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
        }
       
        
       
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (content.Headers.ContentEncoding.Contains("gzip"))
            {
                using (GZipStream gzip = new GZipStream(readStream, CompressionMode.Decompress, true))
                {
                    return base.ReadFromStreamAsync(type, gzip, content, formatterLogger);
                }
            }
            else
            {
                return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
            }
        }

    }
}
